import React from "react"
import {connect} from "react-redux"
import action from "../store/action"
import {message, Form, Button, Input, Collapse, Icon, Select} from 'antd'
import ControllerFun from './ControllerFun'
import ValidatePanel from './ValidatePanel'
import ControllerParams from './ControllerFunParams'
import {fetchFileInfoApi, fetchFunsByFileId, modifyFileInfoApi} from "../api/projectConfig"

const {Panel} = Collapse;
const {TextArea} = Input
const FormItem = Form.Item


const customPanelStyle = {
    background: '#f7f7f7',
    borderRadius: 4,
    marginBottom: 24,
    border: 0,
    overflow: 'hidden',
};

class Controller extends React.Component {

    validatePanel
    controllerParams

    constructor(props) {
        super(props)
        this.state = {
            fileInfo: {},
            fileFunctions: [],
        }
    }

    componentDidMount() {

        let {fileNode} = this.props

        this.fetchFunctionList();
        let fileInfoDataPromit = fetchFileInfoApi(fileNode.fileId)
        fileInfoDataPromit.then(res => {
            let fileInfo = res.data.data
            this.setState({...this.state, fileInfo})
        })
    }

    addCURDToContrl = () => {
        /**
         * 生成增删改查
         * 1、设置增删改查对应的vo；新建域选择已创建VO；
         * 2、设置返回值类型
         * 3、
         */

    }

    fetchFunctionList = () => {
        let {fileNode} = this.props
        fetchFunsByFileId(fileNode.fileId).then(res => {
            let fileFunctions = res.data.data
            this.setState({...this.state, fileFunctions})
        })
    }

    addEmptyFunction = () => {
        let {fileNode} = this.props
        let {fileFunctions} = this.state

        //判断是否有未保存的对象
        let newArray = fileFunctions.filter(item => item.id === undefined)
        if (newArray.length == 0) {

            fileFunctions.push({cid: fileNode.fileId})
            this.setState({...this.state, fileFunctions})
        } else {
            message.warning('请先保存方法，再添加方法！')
        }
    }

    // => 保存存类修改
    saveFileInfo = (e) => {
        e.preventDefault()

        let {fileInfo} = this.state

        const {form} = this.props;

        form.validateFieldsAndScroll((err, values) => {
            if (!err) {

                let formData = this.props.form.getFieldsValue()
                formData.id = fileInfo.id


                let ret = modifyFileInfoApi(formData)
                message.success('保存成功！')
            }
        })




    }

    showControllerParams = (funInfo, argShowCallBack) => {
        this.controllerParams.showModal(funInfo, argShowCallBack)
    }

    showValidatePanel = (argVo) => {
        this.controllerParams.handleCancel()
        this.validatePanel.showPanel(argVo)
    }

    hideValidatePanel = () => {
        this.controllerParams.showModal()
        this.validatePanel.hideValidatePanel()
    }

    doActionControllerFunReturnPopPanel = (type, funInfo, voShowCallBack) => {
        if (type == 'show') {
            this.props.controllerFunReturnPopPanel.show(funInfo, voShowCallBack);
        } else {
            this.props.controllerFunReturnPopPanel.handleCancel();
        }
    }


    render() {

        let {fileFunctions} = this.state


        const formItemLayout = {
            labelCol: {
                xs: {span: 12},
                sm: {span: 3},
            },
            wrapperCol: {
                xs: {span: 12},
                sm: {span: 10},
            },
        }

        const {getFieldDecorator, getFieldValue} = this.props.form

        const text = '0000';

        return (

            <div>
                <span className="code_key">package</span>
                <Form className="form_item_4" onSubmit={this.saveFileInfo}>

                    <FormItem {...formItemLayout} label="类注释">
                        {getFieldDecorator('comment', {
                            initialValue: this.state.fileInfo.comment,
                        })(
                            <TextArea/>
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="请求地址">
                        {getFieldDecorator('reqPath', {
                            initialValue: this.state.fileInfo.reqPath,
                        })(
                            <Input/>
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="类名">
                        {getFieldDecorator('name', {
                            initialValue: this.state.fileInfo.name,
                            rules: [{required: true, message: '请输入类名!'}],
                        })(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="权限控制">
                        {getFieldDecorator('auth', {
                            initialValue: this.state.fileInfo.auth,
                            rules: [{required: true, message: '请选择是否权限控制!'}],
                        })(
                            <Select placeholder="请选择是否权限控制">
                                <Select.Option value="yes">是</Select.Option>
                                <Select.Option value="no">否</Select.Option>
                            </Select>
                        )}
                    </FormItem>

                    {getFieldValue("auth") === "yes" && <>

                        <FormItem {...formItemLayout} label="权限所属">
                            {getFieldDecorator('authType', {
                                initialValue: this.state.fileInfo.authType,
                                rules: [{required: true, message: '请选择权限所属类型!'}],
                            })(
                                <Select placeholder="请选择权限所属类型">
                                    <Select.Option value="Backend">Backend</Select.Option>
                                    <Select.Option value="SysAdmin">SysAdmin</Select.Option>
                                    <Select.Option value="Customer">Customer</Select.Option>
                                    <Select.Option value="Api">Api</Select.Option>
                                    <Select.Option value="App">App</Select.Option>
                                </Select>
                            )}
                        </FormItem>

                        <FormItem {...formItemLayout} label="菜单名称">
                            {getFieldDecorator('menuName', {
                                initialValue: this.state.fileInfo.menuName,
                                rules: [{required: true, message: '请输入菜单名称!'}],
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="路由地址">
                            {getFieldDecorator('routePath', {
                                initialValue: this.state.fileInfo.routePath,
                                rules: [{required: true, message: '请输入路由地址!'}],
                            })(
                                <Input/>
                            )}
                        </FormItem>
                    </>}

                    <Button type="primary" style={{position: "absolute", right: "20px", top: "60px"}}
                            htmlType="submit">保存</Button>
                </Form>


                <Collapse
                    style={{backgroundColor: 'white', marginTop: '30px'}}
                    bordered={true}
                    accordion
                    expandIcon={({isActive}) => <Icon type="caret-right" rotate={isActive ? 90 : 0}/>}
                >

                    {fileFunctions.map((fun, index) =>

                        <Panel header={fun.name + ' ' + ' 【' + fun.returnShow + '】' + fun.reqMethod + ' ' + fun.reqPath}
                               key={fun.id + '100-'} style={customPanelStyle}>
                            <ControllerFun key={fun.id + '000-'}
                                           doActionControllerFunReturnPopPanel={this.doActionControllerFunReturnPopPanel}
                                           showControllerParams={this.showControllerParams} funInfo={fun}
                                           onDelete={() => {
                                               fileFunctions.splice(index, 1)
                                               this.setState({...this.state, fileFunctions: fileFunctions})
                                           }} onUpdateFun={() => {
                                this.fetchFunctionList();
                            }}></ControllerFun>
                        </Panel>
                    )}

                </Collapse>

                <Button onClick={this.addEmptyFunction} type="dashed" block style={{marginTop: "10px"}}> + add
                    function </Button>
                <Button onClick={this.addCURDToContrl} type="dashed" block
                        style={{marginTop: "10px"}}> 生成【增删改查】 </Button>

                {/* params setting */}
                <ControllerParams showValidatePanel={this.showValidatePanel} onRef={(ref) => {
                    this.controllerParams = ref
                }}/>

                {/* 设置参数验证 */}
                <ValidatePanel type="controller" key="validatePanel_key" hideValidatePanel={this.hideValidatePanel}
                               onRef={(ref) => {
                                   this.validatePanel = ref
                               }}/>

            </div>
        )

    }
}

const _Controller = Form.create()(Controller)
export default connect(state => ({...state.controller}), action.controller)(_Controller)
